using System.Collections;

namespace Bzstd.Utility;

/// <summary>
/// 反射工具类
/// </summary>
public static class ReflectionHelper
{
	/// <summary>
	/// 获取应用的泛型类型
	/// </summary>
	/// <param name="genericType"></param>
	/// <param name="srcType"></param>
	/// <returns></returns>
	public static Type GetAppliedGenericType(Type genericType, Type srcType)
	{
		if (genericType.IsInterface)
		{
			return srcType.FindInterfaces((t, _) => t.IsGenericType && genericType == t.GetGenericTypeDefinition(), null).FirstOrDefault();
		}
		else
		{
			var temp = srcType;
			while (!temp!.IsGenericType || genericType != temp.GetGenericTypeDefinition())
			{
				if (temp == srcType.BaseType)
				{
					return null;
				}
				temp = srcType.BaseType;
			}
			return temp;
		}
	}

	/// <summary>
	/// 获取类型名
	/// </summary>
	/// <param name="type"></param>
	/// <returns></returns>
	public static string GetTypeNameSource(Type type)
	{
		while (true)
		{
			if (!type.IsVisible)
			{
				if (typeof(IEnumerable<object>).IsAssignableFrom(type))
				{
					type = GetAppliedGenericType(typeof(IEnumerable<>), type) ?? typeof(object);
					continue;
				}

				if (typeof(IEnumerable).IsAssignableFrom(type))
				{
					type = typeof(IEnumerable);
					continue;
				}

				return "dynamic";
			}

			if (type.IsGenericType)
			{
				return type.FullName!.Split('`').First().Replace('+', '.') + "<" + string.Join(",", type.GenericTypeArguments.Select(GetTypeNameSource)) + ">";
			}

			return type.FullName!.Replace('+', '.');
		}
	}
}
